package utils

import (
	"fmt"
	"framework-server/global"
	"github.com/go-ldap/ldap/v3"
)

type LdapService struct {
	Con *ldap.Conn
}

func NewLdapService() (ls *LdapService, err error) {

	Server := global.GVA_CONFIG.Ldap.Server
	//AdminUser := viper.GetString("ldap.adminuser")
	//AdminPassword := viper.GetString("ldap.adminpassword")
	con, err := ldap.DialURL(Server)

	if err != nil {
		return
	}
	ls = &LdapService{
		Con: con,
	}
	return
}

func (ls *LdapService) Valid(username, password string) (check bool) {
	_, err := ls.Con.SimpleBind(&ldap.SimpleBindRequest{
		Username: username, //"CN=恒大宝,OU=应用系统账号,DC=hdjt,DC=hdad,DC=local"
		Password: password,
	})
	if err != nil {
		check = false
	} else {
		check = true
	}
	return
}

func (ls *LdapService) Check(username, password string) (check bool, userinfo map[string]string) {
	defer ls.Con.Close()
	AdminUser := global.GVA_CONFIG.Ldap.Adminuser
	AdminPassword := global.GVA_CONFIG.Ldap.Adminpassword
	check = true
	if !ls.Valid(AdminUser, AdminPassword) {
		check = false
		return
	}

	searchRequest := ldap.NewSearchRequest(
		global.GVA_CONFIG.Ldap.Basedn,
		ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
		fmt.Sprintf("(sAMAccountName=%v)", username), // 查询所有
		//fmt.Sprintf("(&(objectClass=organizationalPerson)(attributes=%s))",value), // 按属性名查询，属性可在Active Directory 域和信任关系 管理工具中的属性编辑器查看
		[]string{"dn", "cn", "name", "mobile"}, // A list attributes to retrieve
		nil,
	)

	sr, err := ls.Con.Search(searchRequest)
	if err != nil || len(sr.Entries) == 0 {

		check = false
		return
	}

	et := sr.Entries[0]
	dn := et.DN

	//校验用户名和密码
	if !ls.Valid(dn, password) {
		check = false
		return
	}
	userinfo = map[string]string{
		"name":   et.GetAttributeValue("name"),
		"mobile": et.GetAttributeValue("mobile"),
	}
	return
}
